package com.example.demo54acl.service;

import com.example.demo54acl.domain.NoticeMessage;
import com.example.demo54acl.mapper.NoticeMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NoticeMessageService {
    @Autowired
    NoticeMessageMapper noticeMessageMapper;

    /**
     * 注解：@PostFilter("hasPermission(filterObject, 'READ')") 表示在方法返回结果后，过滤掉当前用户没有 READ 权限的通知消息。filterObject 表示集合的每个元素。
     */
    @PostFilter("hasPermission(filterObject, 'READ')")
    public List<NoticeMessage> findAll() {
        return noticeMessageMapper.findAll();
    }

    /**
     * 注解：@PostAuthorize：允许方法调用，但是如果表达式计算结果为false，将抛出一个安全性异常
     */
    @PostAuthorize("hasPermission(returnObject, 'READ')")
    public NoticeMessage findById(Integer id) {
        return noticeMessageMapper.findById(id);
    }

    /**
     * 注解：@PreAuthorize 用于在方法调用之前进行权限检查。如果表达式返回 true，则允许方法执行；否则，会抛出 AccessDeniedException 异常。
     * hasPermission(#noticeMessage, 'CREATE') 是一个 SpEL 表达式。 #noticeMessage 表示方法参数 noticeMessage。'CREATE'、'WRITE' 表示权限。
     */
    @PreAuthorize("hasPermission(#noticeMessage, 'CREATE')")
    public NoticeMessage save(NoticeMessage noticeMessage) {
        noticeMessageMapper.save(noticeMessage);
        return noticeMessage;
    }

    @PreAuthorize("hasPermission(#noticeMessage, 'WRITE')")
    public void update(NoticeMessage noticeMessage) {
        noticeMessageMapper.update(noticeMessage);
    }
}
